import 'dart:async';

import 'package:flutter/services.dart';
import 'package:flutter_jd/config/config.dart';
import 'package:flutter_jd/tools/utils/storage.dart';
import 'package:flutter_jd/tools/utils/utils.dart';
import 'package:flutter_jd/ui/widgets/body/tab_navigator.dart';
import 'package:get/get_state_manager/get_state_manager.dart';
import 'package:get/route_manager.dart';
import 'package:get/get.dart';

class LaunchController extends GetxController {
  Timer? _timer;
  var count = Config.LAUNCH_TIME.obs; // 倒计时（单位：秒）

  @override
  void onInit() {
    super.onInit();
    Utils.hideStatus();
    startTime();
  }

  @override
  void onClose() {
    super.onClose();
  }

  // 倒计时
  void startTime() async {
    Timer(Duration(milliseconds: 0), () {
      _timer = Timer.periodic(const Duration(milliseconds: 1000), (v) {
        --count;
        if (count.value == 0) {
          Timer(Duration(milliseconds: 500), () {
            toHomePage();
          });
        }
      });
    });
  }

  // 跳转到主页
  void toHomePage() {
    if (_timer != null) {
      _timer?.cancel();
      SystemChrome.setEnabledSystemUIOverlays(
        SystemUiOverlay.values,
      );

      setStartTime();

      Get.off(
        () => new TabNavigator(),
        duration: Duration(milliseconds: 600),
        transition: Transition.fadeIn,
      );
    }
  }

  // 缓存APP启动页启动时间
  void setStartTime() {
    StorageUtil().setString('startTime', DateTime.now().toString());
  }
}
